package com.pci.netty.client;

import com.pci.netty.client.channel.ClientNettyChannelInitializer;
import com.pci.netty.enums.MessageTypeEnum;
import com.pci.netty.util.RequestUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class BootNeetyClient {

    private int port;
    private String host;
    private Bootstrap bootstrap;
    private Channel channel;

    public BootNeetyClient(int port, String host) {
        this.port = port;
        this.host = host;
        init();
    }

    public void init() {

        /**
         * 客户端的NIO线程组
         *
         */
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            /**
             * Bootstrap 是一个启动NIO服务的辅助启动类 客户端的
             */
            bootstrap = new Bootstrap();
            /**
             * 设置group
             */
            bootstrap = bootstrap.group(group);
            /**
             * 关联客户端通道
             */
            bootstrap = bootstrap.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
            /**
             * 设置 I/O处理类,主要用于网络I/O事件，记录日志，编码、解码消息
             */
            bootstrap = bootstrap.handler(new ClientNettyChannelInitializer<>(BootNeetyClient.this));

            System.out.println("netty client start success!");

            /**
             * 连接服务端
             */
            //ChannelFuture f = bootstrap.connect(host, port).sync();
            /**
             * 等待连接端口关闭
             */
            //f.channel().closeFuture().sync();

        } finally {
            /**
             * 退出，释放资源
             */
            //group.shutdownGracefully();
        }

    }

    public ChannelFuture connect() throws InterruptedException {
        ChannelFuture f = bootstrap.connect(host, port).sync();
        //断线重连
        f.addListener((ChannelFutureListener) channelFuture -> {
            if (!channelFuture.isSuccess()) {
                final EventLoop loop = channelFuture.channel().eventLoop();
                loop.schedule(() -> {
                    System.out.println("not connect service");
                    try {
                        connect();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }, 1L, TimeUnit.SECONDS);
            } else {
                channel = channelFuture.channel();
                System.out.println("connected");
            }
        });
        return f;
    }


    public static void main(String[] args) throws Exception {
        BootNeetyClient bootNeetyClient = new BootNeetyClient(8888, "127.0.0.1");
        ChannelFuture channelFuture = bootNeetyClient.connect();
        RequestUtils.sendData(MessageTypeEnum.RESTART, "18012201", "19012201", "hello world!", channelFuture);
    }
}
